import {
  message,
  Table,
  Tree,
  Tag,
  Checkbox,
  Pagination,
  Popconfirm,
  Input,
} from "antd";
import Layout from "../Shared/Layout";
import React, { useCallback, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { request, requestDispatch } from "../../Api/api";
import { CarryOutOutlined, PlusOutlined } from "@ant-design/icons";
import AddUser from "../../Components/Operation/User/AddUser";
import MyButton from "../../Components/MyButton";
import { getUserTypeColor, getUserTypeName } from "../../Api/name";
import GiveRight from "../../Components/Operation/User/GiveRight";
const User = () => {
  const [depAndJobTrees, setDepAndJobTrees] = useState([]);
  const [userList, setUserList] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [addingUser, setAddingUser] = useState(null);
  const [giveRightModalVisible, setGiveRightModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState(null);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState({
    page: 1,
    limit: 5,
  });
  const [where, setWhere] = useState({
    key: "",
    isActive: -1,
    isBaned: -1,
    depId: "",
    jobId: "",
    isContainChildren: 0,
    orderField: "",
  });
  const dispatch = useDispatch();
  // 获取所有节点的 key
  const getAllKeys = useCallback((data) => {
    let keys = [];
    data.forEach((item) => {
      keys.push(item.id);
      if (item.childrenDeps) {
        keys = keys.concat(getAllKeys(item.childrenDeps));
      }
    });
    return keys;
  }, []);
  // 将职位加到部门的子级中
  const concatDepJobTree = useCallback((data) => {
    return data.reduce((acc, cur) => {
      const concatChildren = concatDepJobTree(cur.childrenDeps);
      acc.push({
        ...cur,
        selectable: true,
        childrenDeps: [
          ...concatChildren.map((dep) => ({
            ...dep,
          })),
          ...cur.childrenJobs.map((job) => ({
            ...job,
            icon: <CarryOutOutlined />,
            name: (
              <span>
                {job.name}&nbsp;&nbsp;
                <PlusOutlined
                  onClick={(e) => {
                    e.stopPropagation();
                    setAddingUser({
                      depId: cur.id,
                      depName: cur.name,
                      jobId: job.id,
                      jobName: job.name,
                      type: null,
                    });
                    setAddModalVisible(true);
                  }}
                />
              </span>
            ),
          })),
        ],
      });
      return acc;
    }, []);
  }, []);
  // 获取职位树
  const bindJobTree = useCallback(async () => {
    const res = await request("/job/tree", {}, "GET");
    if (res.code >= 0) {
      const concatData = concatDepJobTree(res.data);
      setDepAndJobTrees(concatData);
      setExpandedKeys(getAllKeys(concatData));
    }
  }, [concatDepJobTree, getAllKeys]);
  // 获取用户列表
  const bindUserTable = useCallback(async () => {
    const res2 = await request(
      "/user/pagination",
      { ...page, ...where },
      "GET"
    );
    if (res2.code >= 0) {
      setUserList(res2.data.data.map((item) => ({ ...item, key: item.id })));
      setTotal(res2.data.total);
    }
  }, [page, where]);
  useEffect(() => {
    console.log("change!!!");
    const fetchData = async () => {
      await bindJobTree();
      await bindUserTable();
    };
    fetchData();
  }, [dispatch, bindUserTable, bindJobTree]);
  const banOrStart = async (id, isBaned) => {
    let res = await requestDispatch(
      dispatch,
      `/user/banOrStart`,
      { id, isBaned },
      "POST"
    );
    if (res.code >= 0) {
      message.success(res.message);
      bindUserTable();
    } else {
      message.error(res.message);
    }
  };
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "账号",
      dataIndex: "account",
      key: "account",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
      render: (_, { phone }) => {
        return <span>{phone === "" || phone == null ? "无" : phone}</span>;
      },
    },
    {
      title: "部门",
      dataIndex: "depName",
      key: "depName",
      render: (_, { depId, depName }) => {
        return <span>{depId === "" || depId == null ? "无" : depName}</span>;
      },
    },
    {
      title: "职位",
      dataIndex: "jobName",
      key: "jobName",
      render: (_, { jobId, jobName }) => {
        return <span>{jobId === "" || jobId == null ? "无" : jobName}</span>;
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (_, { createTime }) => {
        return <span>{new Date(createTime).toLocaleString()}</span>;
      },
    },
    {
      title: "类别",
      dataIndex: "type",
      key: "type",
      render: (_, { type }) => {
        return (
          <Tag color={getUserTypeColor(type)}>{getUserTypeName(type)}</Tag>
        );
      },
    },
    {
      title: "是否激活",
      dataIndex: "isActive",
      key: "isActive",
      render: (_, { isActive }) => {
        return (
          <Tag color={isActive === 1 ? "green" : "red"}>
            {isActive === 1 ? "是" : "否"}
          </Tag>
        );
      },
    },
    {
      title: "是否禁用",
      dataIndex: "isBaned",
      key: "isBaned",
      render: (_, { isBaned }) => {
        return (
          <Tag color={isBaned === 1 ? "red" : "green"}>
            {isBaned === 1 ? "是" : "否"}
          </Tag>
        );
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, { id, isBaned, isActive }) => {
        return (
          <div>
            {isBaned === 1 ? (
              <>
                {isActive === 0 ? (
                  <Popconfirm
                    title="删除用户"
                    description="您确定要删除该用户吗？该操作不可恢复。"
                    onConfirm={() => {
                      deleteUser(id);
                    }}
                    okText="Yes"
                    cancelText="No"
                  >
                    <span className="operation-btn">
                      <MyButton type="danger">删除</MyButton>
                    </span>
                  </Popconfirm>
                ) : null}
                <span
                  className="operation-btn"
                  onClick={() => {
                    window.location.href = `/org/user/detail?id=${id}`;
                  }}
                >
                  <MyButton type="primary" className="extra-btn">
                    查看
                  </MyButton>
                </span>
                <span
                  className="operation-btn"
                  onClick={() => {
                    banOrStart(id, 0);
                  }}
                >
                  <MyButton type="success" className="extra-btn">
                    启用
                  </MyButton>
                </span>
              </>
            ) : (
              <>
                <span
                  className="operation-btn"
                  onClick={() => {
                    window.location.href = `/org/user/detail?id=${id}`;
                  }}
                >
                  <MyButton type="primary">查看</MyButton>
                </span>
                <span
                  className="operation-btn"
                  onClick={() => {
                    setCurrentId(id);
                    setGiveRightModalVisible(true);
                  }}
                >
                  <MyButton type="success" className="extra-btn">
                    授权
                  </MyButton>
                </span>
                <span
                  className="operation-btn"
                  onClick={() => {
                    banOrStart(id, 1);
                  }}
                >
                  <MyButton type="warning">禁用</MyButton>
                </span>
              </>
            )}
          </div>
        );
      },
      fixed: "right",
    },
  ];
  // 实际操作
  // 新增用户
  const addUser = async (user) => {
    let res = await requestDispatch(dispatch, "/user/add", user, "POST");
    if (res.code >= 0) {
      message.success(res.message);
      setAddModalVisible(false);
      setAddingUser(null);
      bindUserTable();
    } else {
      message.error(res.message);
    }
  };
  // 删除用户
  const deleteUser = async (id) => {
    let res = await requestDispatch(dispatch, "/user/delete", { id }, "POST");
    if (res.code >= 0) {
      message.success(res.message);
      setUserList(userList.filter((item) => item.id !== id));
      bindUserTable();
    } else {
      message.error(res.message);
    }
  };
  return (
    <Layout>
      <AddUser
        user={addingUser}
        visible={addModalVisible}
        onCancel={() => {
          setAddModalVisible(false);
        }}
        onOk={addUser}
      />
      <GiveRight
        id={currentId}
        open={giveRightModalVisible}
        onCancel={() => {
          setGiveRightModalVisible(false);
        }}
        onOk={async (checkedKeys) => {
          const res = await request(
            "/user/giveRight",
            { id: currentId, rightIds: checkedKeys },
            "POST"
          );
          if (res.code >= 0) {
            message.success(res.message);
            setGiveRightModalVisible(false);
          } else {
            message.error(res.message);
          }
        }}
      />
      <div className="container">
        <div className="container-left">
          <Tree
            showIcon={true}
            treeData={depAndJobTrees}
            expandedKeys={expandedKeys}
            blockNode
            onExpand={(keys) => setExpandedKeys(keys)}
            fieldNames={{ title: "name", key: "id", children: "childrenDeps" }}
            selectedKeys={selectedKeys}
            onSelect={(keys, { node }) => {
              setSelectedKeys(keys);
              if (keys.length !== 0) {
                if (node.childrenDeps != null) {
                  setWhere({ ...where, depId: keys[0], jobId: "" });
                } else {
                  setWhere({ ...where, depId: "", jobId: keys[0] });
                }
              } else {
                setWhere({ ...where, depId: "", jobId: "" });
              }
            }}
          />
        </div>
        <div className="container-right">
          <div className="filter-container">
            <div>
              <Input
                placeholder="请输入关键字"
                width={300}
                allowClear={true}
                value={where.key}
                onChange={(e) => {
                  setWhere({ ...where, key: e.target.value });
                }}
              />
            </div>
            <div className="filter">
              <Checkbox
                checked={where.isContainChildren}
                onChange={(e) => {
                  setWhere({
                    ...where,
                    isContainChildren: e.target.checked ? 1 : 0,
                  });
                }}
              >
                包含子级
              </Checkbox>
            </div>
          </div>
          <Table
            bordered={true}
            sticky={true}
            rowKey={(record) => record.id}
            dataSource={userList}
            columns={columns}
            pagination={false}
            scroll={{ x: "max-content" }}
          ></Table>
          <Pagination
            showQuickJumper
            defaultPageSize={page.limit}
            current={page.page}
            total={total}
            onChange={(pageNumber) => {
              setPage({ ...page, page: pageNumber });
            }}
          />
        </div>
      </div>
    </Layout>
  );
};

export default User;
